package screen;

import java.util.TimeZone;
import java.util.Vector;

import localization.alarmclockResource;
import net.rim.device.api.i18n.ResourceBundle;
import net.rim.device.api.system.Application;
import net.rim.device.api.system.Characters;
import net.rim.device.api.system.PersistentObject;
import net.rim.device.api.system.PersistentStore;
import net.rim.device.api.system.RealtimeClockListener;
import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.DrawStyle;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.TouchEvent;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.CheckboxField;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.EditField;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.ObjectChoiceField;
import net.rim.device.api.ui.component.SeparatorField;
import net.rim.device.api.ui.container.MainScreen;
import code.Config;
import code.Function;
import code.WorldClockSettings;
import ctrl.ForegroundManager;
import ctrl.ListStyleButtonField;
import ctrl.ListStyleButtonSet;
import ctrl.RoundRectFieldManager;

public class NewWorldClockScreen extends MainScreen implements RealtimeClockListener, alarmclockResource
{
	private ForegroundManager _foreground=new ForegroundManager(0);
	private ListStyleButtonSet _buttonSet=new ListStyleButtonSet();
	private EditField _cityName;
	private ObjectChoiceField _timeZoneChoice;
	private LabelField detail;
	private ListStyleButtonField link=new ListStyleButtonField("", "", "");
	private String[] TIMEZONE_DIGITS;
	private CheckboxField _usingDST;

	private int _index;
	private boolean editMode;
	private boolean _isModified=false;
	
	private static PersistentObject _store;
	private static Vector _data=new Vector();
	private static ResourceBundle _resources = ResourceBundle.getBundle(BUNDLE_ID, BUNDLE_NAME);
	
	public NewWorldClockScreen()
	{
		super(USE_ALL_WIDTH | NO_VERTICAL_SCROLL);
	
		setTitle(getResString(TITLE_ADD_NEW_WORLDCLOCK));
		initUI();
		
    	UiApplication.getUiApplication().invokeLater(new Runnable()
    	{
			public void run() {
				_cityName.setDirty(true);		
			}
		});
    	
    	_index=-1;
    	editMode=false;
    	
    	clockUpdated();
	}
	
	public NewWorldClockScreen(WorldClockSettings item, int index)
	{
		super(USE_ALL_WIDTH | NO_VERTICAL_SCROLL);
		
		setTitle(getResString(TITLE_EDIT_WORLDCLOCK));
		initUI();
		
		_cityName.setText(item.getCityName());
		_timeZoneChoice.setSelectedIndex(item.getCurrentIndex());
		
		TimeZone tz=TimeZone.getTimeZone(item.getTimeZone());
    	boolean usingDST=tz.useDaylightTime();
    	_usingDST.setChecked(usingDST);
    	
    	UiApplication.getUiApplication().invokeLater(new Runnable()
    	{
			public void run() {
				_timeZoneChoice.setDirty(false);		
			}
		});
    	
    	_index=index;
    	editMode=true;
	}
	
	private void initUI()
	{
		TIMEZONE_DIGITS=Function.getTimezoneDigits();
		
		RoundRectFieldManager vfm1=new RoundRectFieldManager(), vfm2=new RoundRectFieldManager();

		LabelField settings=new LabelField(getResString(LABEL_TITLE_SETTINGS), USE_ALL_WIDTH | LabelField.ELLIPSIS) {
    		protected void paint(Graphics g)
    		{
    			g.setColor(Color.DARKGRAY);
    			super.paint(g);	
    		}
    	};
    	settings.setFont(Config.FONT_SETTINGS);
    	
    	_cityName=new EditField(getResString(LABEL_CAPTION_SHOW_NAME), getResString(LABEL_SHOW_CONTENT_CITYNAME), 14, EDITABLE | USE_ALL_WIDTH | NON_SPELLCHECKABLE);
    	_cityName.setChangeListener(new FieldChangeListener()
    	{
			public void fieldChanged(Field field, int context) {
				link.setTitleText(_cityName.getText());
			}
		});
    	
    	detail=new LabelField(Config.TIMEZONE_DESCRIPTIONS[0], USE_ALL_WIDTH | DrawStyle.RIGHT);
    	
    	_timeZoneChoice=new ObjectChoiceField(getResString(LABEL_CAPTION_SELECT_TIMEZONE), Config.TIMEZONE_DISPLAY_NAMES){
            protected void fieldChangeNotify(int context)
            {
               	detail.setText(Config.TIMEZONE_DESCRIPTIONS[getSelectedIndex()]);
               	_timeZoneChoice.setDirty(true);
   				clockUpdated();
			}
		};

		_usingDST=new CheckboxField(getResString(LABEL_CAPTION_USE_DST), false, 134217728 | USE_ALL_WIDTH | NON_FOCUSABLE) {
    		protected boolean touchEvent(TouchEvent message) {return true;}
    	};
    	
		vfm1.add(settings);
    	vfm1.add(new SeparatorField());
    	vfm1.add(_cityName);
    	vfm1.add(_timeZoneChoice);
    	vfm1.add(detail);
    	vfm1.add(_usingDST);
		vfm1.setMargin(5,5,5,5);
		vfm1.setPadding(3,5,5,5);
		
    	_buttonSet.add(link);
		
		LabelField sample=new LabelField(getResString(LABEL_TITLE_SAMPLE), USE_ALL_WIDTH | LabelField.ELLIPSIS) {
    		protected void paint(Graphics g)
    		{
    			g.setColor(Color.DARKGRAY);
    			super.paint(g);	
    		}
    	};
    	sample.setFont(Config.FONT_SETTINGS);
    	vfm2.add(sample);
    	vfm2.add(new SeparatorField());
    	vfm2.add(_buttonSet);
		vfm2.setMargin(5,5,5,5);
		vfm2.setPadding(3,5,5,5);
		
    	_foreground.add(vfm1);
    	_foreground.add(vfm2);
		add(_foreground);
		
		_timeZoneChoice.setFocus();
		
		//clockUpdated();
		Application.getApplication().addRealtimeClockListener(this);		
	}
	
	public boolean isModified()
	{
		return _isModified;
	}
	
    private String getResString(int key)
	{
		return _resources.getString(key);
	}
    
    static
   	{
   		_store=PersistentStore.getPersistentObject(0xaa041103a4a17b66L); //blackberry_alarmclock_worldclock_settings_id
   		
   		synchronized(_store)
   		{
   			if(_store.getContents()==null)
   			{
   				_store.setContents(new Vector());
   				_store.forceCommit();
   			}
   		}
   		
   		try {
   			_data=new Vector();
   			_data=(Vector) _store.getContents();
   		} catch (final Exception e) {}
   	}
    
    protected boolean keyChar(char c, int status, int time)
    {
    	if(_cityName.isFocus() && _cityName.getText().equals(getResString(LABEL_SHOW_CONTENT_CITYNAME)) && c==Characters.BACKSPACE)
    	{
    		_cityName.setText("");
    		_cityName.setDirty(true);
    		
    		return true;
    	}
    	
    	return super.keyChar(c, status, time);
    }
    
	protected boolean onSave()
	{
		if(_cityName.getText().equals(""))
		{
			Dialog.alert(getResString(DIALOG_TIPS_CITYNAME_NOT_NONE));
			_cityName.setFocus();
			
			return false;
		}
		
		WorldClockSettings settings=new WorldClockSettings();
		
		settings.setCityName(_cityName.getText());
		settings.setTimeZone(Config.TIMEZONE_IDS[_timeZoneChoice.getSelectedIndex()]);
		settings.setCurrentIndex(String.valueOf(_timeZoneChoice.getSelectedIndex()));
		
		if(editMode)
		{
			int iCount=0;
			
			for(int i=0; i<_data.size(); i++)
			{
				if(_data.elementAt(i) instanceof WorldClockSettings)
				{
					if(iCount==_index)
					{
						_data.setElementAt(settings, i);
						
						i=_data.size()+1;
					}
					
					iCount+=1;
				}
			}
		} else {
			_data.addElement(settings);	
		}
		
		synchronized(_store)
		{
			_store.setContents(_data);
			_store.commit();
		}
		
		_isModified=true;
		
		return true;
	}

	public void clockUpdated()
	{
		int index=_timeZoneChoice.getSelectedIndex();
		TimeZone tz=TimeZone.getTimeZone(Config.TIMEZONE_IDS[index]);
    	String suffix="";
    	boolean usingDST=tz.useDaylightTime();
    	
    	if(usingDST) {suffix=" (DST)";}
		
    	try {
			String[] dateTimeNow=Function.dateTimeNow(tz);
			link.setTitleText(_cityName.getText());
			link.setTimeText(dateTimeNow[1]);
			link.setDateText(dateTimeNow[0] + TIMEZONE_DIGITS[index] + suffix);
			_usingDST.setChecked(usingDST);
    	} catch (Exception e) {}			
	}
}